package edu.qichen.onlineBlog.file.controller;

import cn.hutool.core.util.StrUtil;
import edu.qichen.onlineBlog.framework.DataResult;
import edu.qichen.onlineBlog.framework.OperationAnnotation;
import edu.qichen.onlineBlog.framework.exception.BusinessException;
import edu.qichen.onlineBlog.framework.exception.ErrorCodeEnum;
import edu.qichen.onlineBlog.framework.utils.OSSUtils;
import edu.qichen.onlineBlog.framework.utils.TokenUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 功能:
 * 作者:程序员欧阳子韩
 * 日期:2024/4/19 22:08
 */
@RestController
@RequestMapping("/file")
@Tag(name = "文件接口")
@RequiredArgsConstructor
public class FileController {
    @Autowired
    private OSSUtils ossUtils;

    /**
     * 上传图片
     *
     * @param image -
     * @return -
     * @throws Exception -
     */
    @Operation(summary = "上传图片")
    @PostMapping("/upload")
    @OperationAnnotation(content = "上传图片", sysType = 0, opType = 1, action = "成功")
    public DataResult<?> upload(@RequestParam("file") MultipartFile image, HttpServletRequest request) throws Exception {
        try {
            // 调用阿里云OSS工具类进行文件上传
            String url = ossUtils.picOSS(image);
            if (StrUtil.isBlank(url)) {
                throw BusinessException.build(ErrorCodeEnum.FILE_UPLOAD_ERROR);
            }
            HttpSession session = request.getSession();
            session.setAttribute("username", Objects.requireNonNull(TokenUtils.getCurrentUser()).getUsername());
            return DataResult.success(url);
        } catch (Exception e) {
            return DataResult.fail("文件上传失败，发生异常：" + e.getMessage());
        }
    }
}
